package com.ehotting.eaf.netty.client;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Sharable
public class ConnectorIdleStateTrigger extends ChannelInboundHandlerAdapter {
	
	protected   final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	protected String msg;
	
	
	public ConnectorIdleStateTrigger() {
		super();
	}
	
	public ConnectorIdleStateTrigger(String msg) {
		super();
		this.msg = msg;
	}

	@Override  
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
	    if (evt instanceof IdleStateEvent) {
	         IdleState state = ((IdleStateEvent) evt).state();
	         logger.info("state:{},msg:{},ctx.channel().remoteAddress():{}",state,msg,ctx.channel().remoteAddress());
	         if (state == IdleState.WRITER_IDLE) {
	        	if(msg!=null){
	        		ctx.writeAndFlush(msg);
	        	}
	         }
	         else if (state == IdleState.READER_IDLE) {
	        	  logger.error("readIde read time out,ctx.channel().remoteAddress():{}",ctx.channel().remoteAddress());
	              throw new RuntimeException("readIde read time out");
		     }  
	    } else {
	         super.userEventTriggered(ctx, evt);  
	    }  
	 }

	public void setMsg(String msg) {
		this.msg = msg;
	} 
	
	

    
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
	    //channel失效处理,客户端下线或者强制退出等任何情况都触发这个方法
    	logger.error("Romete server off line,remoteAddress():{}",ctx.channel().remoteAddress());
	    super.channelInactive(ctx);
    }
	

}
